package xyz.ranyh.jobclient.http;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import org.json.JSONObject;
import org.json.JSONTokener;

import okhttp3.Credentials;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import xyz.ranyh.jobclient.ModifyPasswdActivity;
import xyz.ranyh.jobclient.util.Application;

/**
 * Created by rany on 1/3/17.
 */

public class ModifyPasswodTask extends AsyncTask<Void, Void, JSONObject> {
    OkHttpClient client = new OkHttpClient();

    private String mPassword;
    private String mOPassword;
    Context context;

    public ModifyPasswodTask(Context c, String nPassword, String oPassword) {
        mPassword = nPassword;
        mOPassword = oPassword;
        context = c;
    }


    @Override
    protected JSONObject doInBackground(Void... params) {
        String postBody = "{\"old_password\": \"" + mOPassword +"\", \"new_password\": \""+
                mPassword + "\"}";

        RequestBody reqBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), postBody);
        try {
            String credential = Credentials.basic(Resource.getInstance().token, "");
            Request request =  new Request.Builder()
                    .post(reqBody)
                    .url(Url.MODIFY_PASSWORD_URL)
                    .addHeader("Authorization", credential)
                    .addHeader("accept", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            int statusCode = response.code();

            String responseText = response.body().string();

            JSONTokener resJson = new JSONTokener(responseText);
            JSONObject bodyJson = (JSONObject) resJson.nextValue();

            if (statusCode == 200) {

                return bodyJson;
            } else {
                return null;
            }

        } catch (Exception e) {
            Log.d("Register task", e.getMessage());
        }
        return null;
    }
}
